package com.glela.controller;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.util.DateUtil;
import com.glela.domain.ResultVo;
import com.glela.goods.model.request.RequestLimitSaleGoodsListModel;
import com.glela.goods.model.response.ResponseLimitSaleTitle;
import com.glela.goods.model.vo.limitsale.LimitSaleTitleVo;
import com.glela.goods.service.LimitTimeSaleService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

/**
 * 分时抢购
 * @author zls
 *
 */
@RestController
@RequestMapping(value = "fenshigou", produces = "application/json;charset=UTF-8")
public class LimitTimeSaleController extends BaseController {
	/** 用户有效角色id */
	private static final long[] userRoleIds = { 1, 2, 3, 4, 7 };

	@Autowired
	private UserService				userService;
	@Autowired
	private LimitTimeSaleService	limitTimeSaleService;

	/**
	 * <dl>
	 * <dt>分时抢购标题</dt>
	 * </dl>
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月18日 下午3:51:31
	 */
	@RequestMapping(value = "/getLimitSaleTitle", method = RequestMethod.POST)
	public ResponseEntity<?> getLimitSaleTitle(boolean flushCache) {
		String rslt = null;
		try {
			DateTime nowDate = new DateTime();
			if (!flushCache) {
				rslt = queryCacheResult();
			}
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(limitTimeSaleService.findLimitSaleTitle(nowDate));
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询分时抢购标题列表异常:{}", e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(rslt));
	}

	/**
	 * <dl>
	 * <dt>某分时抢购时段下商品列表</dt>
	 * </dl>
	 * @param reqModel
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月18日 下午3:53:21
	 */
	@RequestMapping(value = "/getLimitSaleGoodsList", method = RequestMethod.POST)
	public ResponseEntity<?> getLimitSaleGoodsList(@RequestBody RequestLimitSaleGoodsListModel reqModel, boolean flushCache) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(reqModel.getStatus())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			} else {
				if (ParameterUtils.validParams(reqModel.getLimitTimeSaleId())) {
					if (reqModel.getStatus() == 2 || reqModel.getStatus() == 3) {
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
					}
				}
			}
			reqModel.setPageSize(20);
			ResponseUser loginUser = null;
			if (reqModel.getUserId() != null && reqModel.getUserId() > 0) {
				//				loginUser = userService.selectUserRoleById(reqModel.getUserId());
				try {
					loginUser = userService.selectUserRoleFormCacheById(reqModel.getUserId());
				} catch (Exception e) {
					getLOGGER().error("分时购列表，用户无效{}不存在", reqModel.getUserId());
				}
			}
			if (loginUser == null) {
				tempKey = getTempCacheKey(reqModel.getStatus(), reqModel.getLimitTimeSaleId(), 0, reqModel.getPageNum());
			} else {
				tempKey = getTempCacheKey(reqModel.getStatus(), reqModel.getLimitTimeSaleId(), loginUser.getRoleId(), reqModel.getPageNum());
			}

			if (!flushCache) {
				rslt = queryCacheResult(tempKey);
			}
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(limitTimeSaleService.findLimitSaleGoodsList(reqModel, loginUser, new DateTime()));
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询分时抢购标题列表异常:{}", e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt));
	}

	/**
	 * <dl>
	 * <dt>明日预告商品总条数</dt>
	 * </dl>
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月14日 下午3:47:06
	 */
	@RequestMapping(value = "/getTomorrowTrailerGoodsNums")
	public ResponseEntity<?> getTomorrowTrailerGoodsNums() {
		String rslt = null;
		try {
			rslt = queryCacheResult();
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(limitTimeSaleService.findTomorrowTrailerGoodsNums());
			} else {
				return toRespEntity(rslt);
			}
			//			return new ResponseEntity<>(new ResponseResultModel<>(limitTimeSaleService.findTomorrowTrailerGoodsNums()), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("查询分时抢购标题列表异常:{}", e.getMessage(), e);
			//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(rslt));
	}

	/**
	 * <dl>
	 * <dt>明日预告商品信息</dt>
	 * <dd>店主级别查看明日预告商品信息</dd>
	 * </dl>
	 * @param reqModel
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月14日 下午2:42:21
	 */
	@RequestMapping(value = "/getTomorrowTrailer", method = RequestMethod.POST)
	public ResponseEntity<?> getTomorrowTrailer(@RequestBody RequestLimitSaleGoodsListModel reqModel) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(reqModel.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isNotBlank(reqModel.getStartTime())) {
				try {
					if (DateUtil.parse(reqModel.getStartTime()) == null) {
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
					}
				} catch (Exception e) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
				}
			}

			tempKey = getTempCacheKey(reqModel.getStartTime(), reqModel.getPageSize());
			rslt = queryCacheResult(tempKey);

			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(limitTimeSaleService.getTomorrowTrailer(reqModel));
			} else {
				return toRespEntity(rslt);
			}
			//			return new ResponseEntity<>(new ResponseResultModel<>(limitTimeSaleService.getTomorrowTrailer(requestLimitSaleGoodsListModel)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("查询分时抢购明日预告列表异常:{}", e.getMessage(), e);
			//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt));
	}

	/**
	 * <dl>
	 * <dt>初始化分时抢购标题</dt>
	 * </dl>
	 * @return ResultVo
	 * @author zls
	 * @date 2018年1月12日 上午11:17:08
	 */
	@RequestMapping(value = "/initLimitTitle", method = RequestMethod.POST)
	public @ResponseBody ResultVo initLimitTitle() {
		ResultVo rslt = new ResultVo();
		try {
			getLimitSaleTitle(true);
			rslt.setSuccess(true);
		} catch (Exception e) {
			getLOGGER().error("初始化分时抢购标题失败：{}", e.getMessage(), e);
			rslt.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 20));
		}
		return rslt;
	}

	/**
	 * <dl>
	 * <dt>初始化分时购列表</dt>
	 * </dl>
	 * @author zls
	 * @date 2018年1月3日 下午7:50:13
	 */
	@RequestMapping(value = "/initLimitGoodsList", method = RequestMethod.POST)
	public @ResponseBody ResultVo initLimitGoodsList() {
		ResultVo rslt = new ResultVo();
		try {
			List<Long> userIdEmun = userService.getUserRoleEnum(userRoleIds);
			ResponseEntity<?> limitSaleTitle = getLimitSaleTitle(false);
			JSONObject parseObject = JSONObject.parseObject(limitSaleTitle.getBody().toString());
			if (MapUtils.isNotEmpty(parseObject) && StringUtils.equals(parseObject.getString("code"), Long.toString(ErrorEnum.C10000.getCode()))) {
				ResponseLimitSaleTitle findLimitSaleTitle = parseObject.getObject("data", ResponseLimitSaleTitle.class);
				//				ResponseLimitSaleTitle findLimitSaleTitle = limitTimeSaleService.findLimitSaleTitle(new DateTime());
				if (findLimitSaleTitle != null && CollectionUtils.isNotEmpty(findLimitSaleTitle.getTitles())) {
					//取当前默认展示分时抢购
					if (findLimitSaleTitle.getTitles().size() > findLimitSaleTitle.getShowDefIndex()) {
						LimitSaleTitleVo limitSaleTitleVo = findLimitSaleTitle.getTitles().get(findLimitSaleTitle.getShowDefIndex());
						if (limitSaleTitleVo != null && limitSaleTitleVo.getStatus() == 2) {//如果是进行时，刷新
							RequestLimitSaleGoodsListModel reqModel = new RequestLimitSaleGoodsListModel();
							reqModel.setLimitTimeSaleId(limitSaleTitleVo.getLimitTimeSaleId());
							reqModel.setStatus(limitSaleTitleVo.getStatus());
							for (int i = 0; i < 3; i++) {
								for (long userId : userIdEmun) {
									reqModel.setUserId(userId);
									reqModel.setPageNum(i + 1);
									getLimitSaleGoodsList(reqModel, true);
								}
							}
						}
					}
				}
			}
			rslt.setSuccess(true);
		} catch (Exception e) {
			rslt.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 20));
			getLOGGER().error("刷新分时购商品列表失败：{}", e.getMessage(), e);
		}
		return rslt;
	}

}